package com.github.lzyzsd.jsbridge.example;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements OnClickListener {
    private final String TAG = "MainActivity";
    private final int RESULT_CODE = 0;
    private BridgeWebView webView;
    private Button button4, button0, button, button2;
    private ValueCallback<Uri> mUploadMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (BridgeWebView) findViewById(R.id.webView);
        button4 = (Button) findViewById(R.id.button4);
        button0 = (Button) findViewById(R.id.button0);
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        button4.setOnClickListener(this);
        button0.setOnClickListener(this);
        button.setOnClickListener(this);
        button2.setOnClickListener(this);

        initSettings();

//        webView.setDefaultHandler(new DefaultHandler());
        webView.setDefaultHandler(new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i(TAG, "setDefaultHandler data from web = " + data);
                function.onCallBack("setDefaultHandler Java 数据");
                ToastUtils.showShort("JS返回: %s", data);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                this.openFileChooser(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                pickFile();
            }
        });
        webView.setWebViewClient(new BridgeWebViewClient(webView) {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    url = URLDecoder.decode(url, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (url.startsWith("fcw://")) {
                    Log.i(TAG, "shouldOverrideUrlLoading-url: " + url + "  true");
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                boolean b = super.shouldOverrideUrlLoading(view, url);
                Log.i(TAG, "shouldOverrideUrlLoading-url: " + url + "  " + b);
                return b;
            }
        });

        webView.loadUrl("file:///android_asset/demo.html");

        final List<OnBindHandler> binds = getBinds();
        for (OnBindHandler bindHandler : binds) {
            bindHandler.bindHandler(webView);
        }

        webView.send("hello");

    }

    public void pickFile() {
        Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
        chooserIntent.setType("image/*");
        startActivityForResult(chooserIntent, RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        //绑定Handlers
        final List<OnBindHandler> binds = getBinds();
        for (OnBindHandler bindHandler : binds) {
            bindHandler.onActivityResult(requestCode, resultCode, intent);
        }

        if (requestCode == RESULT_CODE) {
            if (null == mUploadMessage) {
                return;
            }
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if (button4.equals(v)) {
            Intent i = new Intent();
            i.setAction("android.intent.action.VIEW");
            i.addCategory("android.intent.category.DEFAULT");
            i.addCategory("android.intent.category.BROWSABLE");
            i.setData(Uri.parse("fcw://td.fcw.com/openChat?id=0000&param=JS-param"));
            //intent://td.fcw.com/openChat?id=0000&param=JS-param#Intent;scheme=fcw;category=android.intent.category.DEFAULT;category=android.intent.category.BROWSABLE;end
            Log.i(TAG, i.toUri(Intent.URI_INTENT_SCHEME));
        }
        if (button0.equals(v)) {
            startFCWApp();
        }
        if (button.equals(v)) {
            webView.callHandler("functionInJs", "Java 入参", new CallBackFunction() {
                @Override
                public void onCallBack(String data) {
                    Log.i(TAG, "callHandler handler = functionInJs, data from web = " + data);
                    ToastUtils.showShort("JS返回: %s", data);
                }
            });
        }
        if (button2.equals(v)) {
            webView.callHandler("getWebInput", null, new CallBackFunction() {
                @Override
                public void onCallBack(String data) {
                    Log.i(TAG, "callHandler handler = getWebInput, data from web = " + data);
                    ToastUtils.showShort("JS返回: %s", data);
                }
            });
        }
    }

    /**
     * 打开FCWApp
     */
    private void startFCWApp() {
        try {
            String url = "fcw://td.fcw.com/openChat?id=10011002&param=JS返回参数";
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("您还未安装该App");
        }
    }

    /**
     * 绑定任务集合
     */
    private List<OnBindHandler> getBinds() {
        ArrayList<OnBindHandler> handlers = new ArrayList<>();
        handlers.add(PlatformInfo.getInstance());
        handlers.add(SubmitFromWeb.getInstance());
        handlers.add(FunctionInJs.getInstance());

        return handlers;
    }

    /**
     * webView初始化设置
     */
    private void initSettings() {
        WebView.setWebContentsDebuggingEnabled(true);
        WebSettings settings = webView.getSettings();
        // 允许加载本地文件
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//自动打开窗口
        settings.setSupportZoom(true);//是否支持缩放
        settings.setBuiltInZoomControls(true);//是否支持缩放
        settings.setDisplayZoomControls(false);//是否显示内置缩放控件
        settings.setUseWideViewPort(true);//扩大比例的缩放  当值为true且viewport标签不存在或未指定宽度时使用 wide viewport mode

        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);//是否使用overview mode加载页面，默认值 false，当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度

        settings.setAppCacheEnabled(false);//设置是否启用应用程序缓存api
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);//设置是否启用了DOM storage API。

        webView.setInitialScale(20);
    }
}
